package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author zsk
 * @create 2022-02-18-20:04
 */
@RestController
public class AddressController {

    //依赖注入
    @Autowired
    private AddressService addressService;

    /*
    查询地址信息
    Request URL: http://localhost:8081/address/list
    Request Method: GET
     */
    @GetMapping("/address/list")
    public ResultInfo findList(){
        List<Address> addressList = addressService.findList();
        return ResultInfo.success(addressList);
    }

    /*
    新增地址
    Request URL: http://localhost:8081/address
    Request Method: POST
     */
    @PostMapping("/address")
    public ResultInfo save(@RequestBody Address address){

        //调用service层添加
        addressService.save(address);

        //返回结果
        return ResultInfo.success(null);
    }

    /*
    修改默认地址
    Request URL: http://localhost:8081/address/default
    Request Method: PUT
     */
    @PutMapping("/address/default")
    public ResultInfo setDefault(@RequestBody Map<String,Long> map){

        //获取id
        Long id = map.get("id");

        //调用service层修改
        addressService.setDefault(id);

        //返回结果
        return ResultInfo.success(null);
    }
    /*
    查询默认地址
     */
    @GetMapping("/address/default")
    public ResultInfo findDefault(){
        //调用service层查询
        Address address = addressService.findDefault();
        if (address == null ){
            return ResultInfo.error("没有设置默认地址");
        }else {
            //返回默认地址结果
            return ResultInfo.success(address);
        }
    }

    /*
    修改数据前回显数据
    Request URL: http://localhost:8081/address/1417414526093082626
    Request Method: GET
     */
    @GetMapping("/address/{id}")
    public ResultInfo findById(@PathVariable("id") Long id){

        //调用service查询
        Address address = addressService.findById(id);

        //返回结果
        return ResultInfo.success(address);

    }

    /*
    修改数据
    Request URL: http://localhost:8081/address
    Request Method: PUT
     */
    @PutMapping("/address")
    public ResultInfo update(@RequestBody Address address){

        //调用service修改
        addressService.update(address);

        //返回结果
        return ResultInfo.success(null);

    }

    /*
    删除地址
    Request URL: http://localhost:8081/address?ids=1417414526093082626
    Request Method: DELETE
     */
    @DeleteMapping("/address")
    public ResultInfo deleteById(Long ids){

        //调用service层删除
        addressService.deleteById(ids);

        //返回结果
        return ResultInfo.success(null);
    }

}
